<?php
/**
 * 用文件来实现缓存
 * @author	ronnie  (comdeng@gmail.com)
 * @link		http://fillphp.com/
 * @date		2014-5-3 下午11:16:29
 * @file		newfile.php
 * @description 
 */
namespace fillphp\helper;

class FileCache extends \fillphp\helper\Helper
{
	private $tmpDir;
	
	function setTmpDir($tmpDir)
	{
		$this->tmpDir = $tmpDir;
	}
	
	private function getFilePath($uri)
	{
		if (!$this->tmpDir) {
			throw new \Exception(__NAMESPACE__.':tmpDirNotDefined');
		}
		$cacheFile = hash('sha1', $uri);
		return sprintf('%s/%s/%s.phtml', $this->tmpDir, substr($cacheFile, 0, 2), substr($cacheFile, 2));
	}
	
	/**
	 * 设置缓存内容
	 * @param string $uri
	 * @param string $content
	 */
	function set($uri, $content)
	{
		$path = $this->getFilePath($uri);
		$dir = dirname($path);
		if (!is_dir($dir)) {
			mkdir($dir, 0755);
		}
		file_put_contents($path, $content);
	}
	
	/**
	 * 获取缓存内容
	 * @param string $uri
	 * @param int $expire
	 * @return NULL|string
	 */
	function get($uri, $expire)
	{
		$path = $this->getFilePath($uri);
		if (!is_readable($path)) {
			return NULL;
		}
		if (filemtime($path) + $expire < time()) {
			return NULL;
		}
		return file_get_contents($path);
	}
}
